package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;

    //事务回滚
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        // 扩展方法
        // 保存套餐基本信息,一个套餐包含多个菜品
        log.info("[新增套餐],dto：{}",setmealDto);
        this.save(setmealDto);
        // 保存套餐菜品关系列表，批量保存
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish>  setmealDishList = setmealDishes.stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishList);
    }


    @Transactional
    @Override
    public void removeWithDish(List<Long> ids) {
        // 扩展业务类
        // 删除套餐列表（套餐表）Setmeal表
        // 删除的时候，是否需要关联关系
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        // 1正在使用，不能删除
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);

        // 基于条件查询
        int count = this.count(setmealLambdaQueryWrapper);
        if (count > 0){
            throw new CustomException("套餐正在售卖，不能删除");
        }
        // 批量删除套餐，基于id删除
        this.removeByIds(ids);
        // 删除套餐菜品关系表（关系表）SetmealDish表
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        // 基于条件删除
        setmealDishService.remove(setmealDishLambdaQueryWrapper);

    }
}
